﻿using Microsoft.AspNetCore.Http;
using SBlogCore.Common.FriendlyException;

namespace SBlogCore.Common.FileUploadExtend
{
    public class FileUploadContext
    {
        public FileUploadContext(IFormFile file)
        {
            this.FormFile = file ?? throw SBlogCoreException.Say("文件数据不能为空");
        }
        /// <summary>
        /// 文件
        /// </summary>
        public IFormFile FormFile  { get; init; }
        /// <summary>
        /// 文件名
        /// </summary>
        public string GetFileName=> Path.GetFileName(FormFile.FileName);
        /// <summary>
        /// 读取文件为流
        /// </summary>
        /// <returns></returns>
        public async Task<byte[]> ReadFileToStream()
        {
            var sourceStream = FormFile.OpenReadStream();
            byte[] result = new byte[sourceStream.Length];
            _ = await sourceStream.ReadAsync(result, 0, (int)sourceStream.Length);
            //using var binaryReader = new BinaryReader(FormFile.OpenReadStream());
            //var fileBuffers = binaryReader.ReadBytes((int)FormFile.Length);
            return result;
        }
        /// <summary>
        /// 文件大小
        /// </summary>
        public long FileLength=> FormFile.Length;
    }
}
